from os.path import join, dirname
from PyQt5 import QtCore
from PyQt5.QtGui import QPixmap, QPalette, QBrush
from PyQt5.QtWidgets import QWidget, QApplication
from ui_test2 import Ui_Form

def set_widget_background_full(widget: QWidget, img_path: str):
    """
    背景图片按窗口大小拉伸填满窗体

    Args:
        widget (QWidget):设置的目标对象
        img_path (str): 图片路径
    """
    palette = QPalette()
    palette.setBrush(widget.backgroundRole(), QBrush(
        QPixmap(img_path).scaled(
            widget.size(),
            QtCore.Qt.IgnoreAspectRatio,
            QtCore.Qt.SmoothTransformation
        )))
    widget.setPalette(palette)

def set_widget_background_regular(widget: QWidget, img_path: str):
    """
    背景图片按原大小铺满窗体

    Args:
        widget (QWidget):设置的目标对象
        img_path (str): 图片路径
    """
    palette = QPalette()
    palette.setBrush(QPalette.Background, QBrush(QPixmap(img_path)))
    widget.setPalette(palette)

class MyTest(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        back_img = join(dirname(__file__), 'res', 'back.png')
        set_widget_background_full(self, back_img)
        # set_widget_background_regular(self, back_img)


app = QApplication([])
test = MyTest()
test.show()
app.exec_()
